package com.ruoyi.program.controller;

import com.ruoyi.common.annotation.Anonymous;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
import com.ruoyi.program.service.ICreateNameOrderService;

import com.ruoyi.program.domain.CreateNameOrder;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONArray;
import java.util.HashMap;
import java.util.Map;
import org.springframework.web.bind.annotation.RequestBody;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

@Anonymous
@RestController
public class AlipayReceiveSignNotifyController {

  // @Value("${alipay.public-key}")
  // private String alipayPublicKey;
  @Autowired
  private ICreateNameOrderService createNameOrderService;

  @PostMapping("/alipayapi/api/notify")
  public String handleAlipayCallback(@RequestParam Map<String, String> params) {
    System.out.println("收到支付宝回调通知：" + params);

    // 拿到trade_status，判断是否交易成功，如果成功，则更新订单状态
    String tradeStatus = params.get("trade_status");
    String outTradeNo = params.get("out_trade_no");
    Date payTime = new Date();
    System.out.println("outTradeNo======" + outTradeNo);
    System.out.println("tradeStatus=====" + tradeStatus);

    if ("TRADE_SUCCESS".equals(tradeStatus)) {
      // 代表支付成功状态码为2
      Integer sta = 2;
      int status = createNameOrderService.updateNameOrderService(sta, outTradeNo, payTime);
      System.out.println("订单状态更新成功，更新结果状态码: " + status);
      if (status == 2) {
        System.out.println("订单状态更新成功，更新结果状态码: " + status);
      } else {
        System.out.println("订单状态更新失败，更新结果状态码: " + status);
      }
    }
    return "success";

    // 收到支付宝回调通知：
    /**
     * {gmt_create=2025-04-23 16:35:49,
     * charset=utf-8,
     * seller_email=427891042@qq.com,
     * subject=起名字,
     * sign=ba1yuh6jNnQaS2Sd0AoDltIv2KKq8Xf8zXYbwQH+T/FaVwxwzgdYCO8NJ7dLv96eBZOUrxGbA3OSLyWjnG5kMcX9GjzVQ2S19IuY/RwOiX7Yb934FK3uuuLZjKzpLF+ySMyhz6kn72bLFsjxS382+sUKjEsYrv7MwNqOdwjDXjt3MNxrcSnwmUAy3sESILutIKHFnjeCIEwp0NEMKsxh+yIWY1Jsz8yTFI1ohcU/o/J1dfRPVHwdiecac0/WiMl4eMXIFVMw3Yb4pzULdFYkAqLLiwoUL+wtMQatXsEPbZoCoUTBTcjIR58TRlSOTy9MbgM25pkJ3Q1zPMb1fC/zZw==,
     * buyer_id=2088412051171383,
     * invoice_amount=0.01,
     * notify_id=2025042301222163559071381426067589,
     * fund_bill_list=[{"amount":"0.01","fundChannel":"ALIPAYACCOUNT"}],
     * notify_type=trade_status_sync,
     * trade_status=TRADE_SUCCESS,
     * receipt_amount=0.01,
     * buyer_pay_amount=0.01,
     * app_id=2021005123678059,
     * sign_type=RSA2,
     * seller_id=2088941508616075,
     * gmt_payment=2025-04-23 16:35:59,
     * notify_time=2025-04-23 16:35:59,
     * version=1.0,
     * out_trade_no=QM2025042316354882,
     * total_amount=0.01,
     * trade_no=2025042322001471381443692296,
     * auth_app_id=2021005123678059,
     * buyer_logon_id=155****5130,
     * point_amount=0.00}
     */

  }

  @PostMapping("/alipayapi/api/nameOrder")
  // 通过用户传入的订单号查询订单信息 返回一个对象给前端
  // {tradeNO: "2025042722001471381401617146"} 前端传入的参数
  // 修改为使用 @RequestBody
  // 导入 @RequestBody 注解所在的包
  public Map<String, Object> queryNameOrder(@RequestBody Map<String, String> params) {
    System.out.println("查询订单信息params：" + params);
    String tradeNO = params.get("tradeNO");
    System.out.println("查询订单信息tradeNO：" + tradeNO);

    // 调用服务层方法获取订单信息
    // 修改为使用 tradeNO 变量
    CreateNameOrder order = (CreateNameOrder) createNameOrderService.selectNameOrderService(tradeNO);
    System.out.println("查询订单信息order：" + order);

    // 将订单信息转换为 Map<String, Object> 类型
    Map<String, Object> result = new HashMap<>();
    if (order != null) {
      result.put("surname", order.getSurname());
      result.put("sex", order.getSex());
      result.put("type", order.getType());
      result.put("birthday", order.getBirthday());
      result.put("userId", order.getUserId());
      result.put("appid", order.getAppid());
      result.put("productId", order.getProductId());
      result.put("productPrice", order.getProductPrice());
      result.put("productNumber", order.getProductNumber());
      result.put("totalPrice", order.getTotalPrice());
      result.put("subject", order.getSubject());
      result.put("status", order.getStatus());
      result.put("orderNo", order.getOrderNo());
      result.put("createTime", order.getCreateTime());
      result.put("payTime", order.getPayTime());
      result.put("closeTime", order.getCloseTime());
      result.put("productOriginalPrice", order.getProductOriginalPrice());

      // 调用起名接口
      // List<String> allNames = new ArrayList<>(); // 移除多余列表
      Set<String> uniqueNames = new HashSet<>(); // 用于去重
      try {
        String key = "aGPUwVr4qIPEz16qqpKIMc6rHJ"; // 请替换为实际的接口密钥
        String surname = order.getSurname();
        String sex = String.valueOf(order.getSex());
        Date birthdayDate = order.getBirthday();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String birthday = sdf.format(birthdayDate);
        String type = String.valueOf(order.getType());
        String quantity = "30";

        // 最多调用4次API（4×30=120），确保能获取足够不重复名字
        for (int i = 0; i < 4; i++) {
          // 添加随机参数避免API返回重复结果
          String url = "https://qqlykm.cn/api/qiming/index?"
              + "key=" + URLEncoder.encode(key, "utf-8")
              + "&surname=" + URLEncoder.encode(surname, "utf-8")
              + "&sex=" + URLEncoder.encode(sex, "utf-8")
              + "&birthday=" + URLEncoder.encode(birthday, "utf-8")
              + "&type=" + URLEncoder.encode(type, "utf-8")
              + "&quantity=" + URLEncoder.encode(quantity, "utf-8")
              + "&random=" + System.currentTimeMillis(); // 添加随机参数

          URL obj = new URL(url);
          HttpURLConnection con = (HttpURLConnection) obj.openConnection();
          con.setRequestMethod("GET");
          con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

          BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
          String inputLine;
          StringBuilder response = new StringBuilder();
          while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
          }
          in.close();

          // 解析返回的 JSON 数据
          JSONObject jsonResponse = JSONObject.parseObject(response.toString());
          JSONObject data = jsonResponse.getJSONObject("data");
          JSONArray namesArray = data.getJSONArray("list");

          // 直接添加到去重集合
          for (int j = 0; j < namesArray.size(); j++) {
            JSONObject nameObj = namesArray.getJSONObject(j);
            String name = nameObj.getString("name");
            uniqueNames.add(name); // 添加到Set实现去重
            // 达到100个时停止
            if (uniqueNames.size() >= 100)
              break;
          }
          if (uniqueNames.size() >= 100)
            break; // 达到数量提前终止循环
        }

        // 转换为List（保持顺序）
        List<String> distinctNames = new ArrayList<>(uniqueNames);
        // 截取前100个（防止超过需求）
        if (distinctNames.size() > 100) {
          distinctNames = distinctNames.subList(0, 100);
        }

        // 使用去重后的列表生成字符串
        String namesStr = String.join(",", distinctNames);

        Map<String, Object> insertParams = new HashMap<>();
        insertParams.put("namesStr", namesStr);
        insertParams.put("orderNo", order.getOrderNo());
        createNameOrderService.insertNamesByOrderNo(insertParams);

        result.put("names", distinctNames); // 返回去重后的列表
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    // 添加返回语句
    return result;
    // public int queryNameOrderService(@RequestParam Map<String, String> params) {
    // System.out.println("查询订单信息：" + params);
    // String outTradeNo = params.get("out_trade_no");
    // }
  }

  @PostMapping("/alipayapi/api/queryUserNames")
  public Map<String, Object> queryUserNames(@RequestBody Map<String, String> params) {
    System.out.println("查询订单信息params：" + params);

    String birthday = params.get("birthday");
    String surname = params.get("surname");
    String name = params.get("name");
    String key = "aGPUwVr4qIPEz16qqpKIMc6rHJ"; // 请替换为实际的接口密钥

    try {
      // 对参数进行编码
      String encodedBirthday = java.net.URLEncoder.encode(birthday, "utf-8");
      String encodedSurname = java.net.URLEncoder.encode(surname, "utf-8");
      String encodedName = java.net.URLEncoder.encode(name, "utf-8");
      String encodedKey = java.net.URLEncoder.encode(key, "utf-8");

      String url = "https://qqlykm.cn/api/qiming/index?" + "birthday=" + encodedBirthday + "&surname=" + encodedSurname
          + "&name="
          + encodedName + "&key=" + encodedKey;

      URL obj = new URL(url);
      HttpURLConnection con = (HttpURLConnection) obj.openConnection();
      con.setRequestMethod("GET");
      con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

      int responseCode = con.getResponseCode();
      Map<String, Object> result = new HashMap<>();
      if (responseCode == HttpURLConnection.HTTP_OK) {
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
          response.append(inputLine);
        }
        in.close();

        // 解析返回的 JSON 数据
        com.alibaba.fastjson2.JSONObject jsonResponse = com.alibaba.fastjson2.JSONObject
            .parseObject(response.toString());
        result.put("code", 200);
        result.put("data", jsonResponse);
      } else {
        result.put("code", responseCode);
        result.put("msg", "请求失败，状态码：" + responseCode);
      }
      return result;
    } catch (Exception e) {
      Map<String, Object> result = new HashMap<>();
      result.put("code", 500);
      result.put("msg", "请求发生异常：" + e.getMessage());
      return result;
    }
  }

  // 通过用户传入的userId查询订单列表
  @PostMapping("/alipayapi/api/queryUserOrder")
  public Map<String, Object> queryUserOrder(@RequestBody Map<String, String> params) {
      System.out.println("查询订单列表params：" + params);
      String userId = params.get("userId");
      String statusStr = params.get("status");
      Integer status = statusStr != null ? Integer.valueOf(statusStr) : null;
      
      // 构建结果Map，统一返回格式
      Map<String, Object> result = new HashMap<>();
      
      // 添加userId非空校验
      if (userId == null || userId.trim().isEmpty()) {
          result.put("code", 400);
          result.put("msg", "请登录后再查询订单信息");
          return result;
      }
      
      System.out.println("查询订单列表userId：" + userId);
      System.out.println("查询订单列表status：" + status);
      
      // 调用服务层方法获取订单信息
      List<CreateNameOrder> orders = createNameOrderService.selectUserOrderListService(userId, status);
      
      result.put("code", 200);
      result.put("msg", "查询成功");
      result.put("data", orders);
      return result;
  }

  /*
   * // 通过用户传入的订单号tradeNo查询订单列表
   */
  @PostMapping("/alipayapi/api/queryOrderDetails")
  public Map<String, Object> queryNameOrderDetails(@RequestBody Map<String, String> requestBody) {
    System.out.println("requestBody" + requestBody);
    String orderNo = requestBody.get("orderNo");
    System.out.println("用户输入的orderNo:========" + orderNo);
    java.util.Map<String, Object> result = new java.util.HashMap<>();
    if (orderNo == null) {
      result.put("code", 400);
      result.put("msg", "订单号不能为空");
      return result;
    }
    CreateNameOrder order = createNameOrderService.selectNameDetailsByOrderNo(orderNo);
    System.out.println("order==============" + order);
    if (order != null) {
      result.put("code", 200);
      result.put("msg", "查询成功");
      result.put("data", order);
    } else {
      result.put("code", 404);
      result.put("msg", "未找到对应的订单信息");
    }
    return result;
  }

}
